//; mapshader.fx written by Alex Anderson
//; @15.8.12

// ################
// ### Varibles ###
float4x4 World;
float4x4 View;
float4x4 Projection; 

bool Hover;
float HoverHeight;

float4 AmbientColor;
float AmbientLevel;

float3 DiffuseDirection;
float4 DiffuseColor;
float4 DiffuseLevel;

Texture CellTexture;
sampler TextureSampler = sampler_state { texture = <CellTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};

// ## Used to sample the Selection Texture (white cross hatching)
bool ShowSelection;
float4 SelectionGridColor;
Texture SelectionIndicator;
sampler SelectionSampler = sampler_state { texture = <SelectionIndicator> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};


// #######################
// ### Data Structures ###
struct VertexData {
	float4 Position : POSITION;
	float2 UV : TEXCOORD0;
	float3 Normal : TEXCOORD1;
	float3 Position3D : TEXCOORD2;
};

struct PixelData {
	float4 Color : COLOR0;
};

// ########################
// ### Shader Functions ###
VertexData CellVertexShader(float4 inPos : POSITION0, float3 inNormal: NORMAL0, float2 inTexCoords : TEXCOORD0)
{
	VertexData output = (VertexData)0;

	float4x4 vp = mul(View, Projection);
	float4x4 wvp = mul(World, vp);

	float4 position = mul(inPos, wvp).xyzw;
	if(Hover)
		position.y += HoverHeight;

	output.Position = position;
	output.UV = inTexCoords;
	output.Normal = normalize(mul(inNormal, (float3x3)World));
	output.Position3D = mul(inPos, World);

	return output;
}

PixelData CellPixelShader(VertexData inData)
{
	PixelData output = (PixelData)0;	
	float4 textureColor = tex2D(TextureSampler, inData.UV).rgba;	
	 
	float4 selectColor = tex2D(SelectionSampler, inData.UV).rgba;
	selectColor *= SelectionGridColor; 

	float4 outputColor = textureColor;

	if(ShowSelection) {
		if(selectColor.a == 0.0f)
			outputColor = textureColor;
		else
			outputColor = selectColor;
	}

	float4 norm = float4(inData.Normal, 1.0);
	float4 diffuse = saturate(dot(-DiffuseDirection, norm));

	output.Color = 
		(outputColor * (AmbientColor * AmbientLevel));
		//(outputColor * (DiffuseLevel * DiffuseColor * diffuse));

	return output;
} 

// ##################
// ### Techniques ###
technique CellShade
{
	pass Pass0
	{
		VertexShader = compile vs_2_0 CellVertexShader();
		PixelShader = compile ps_2_0 CellPixelShader();
	}
}